package com.rk.kbk.controller.wxutils;


import com.alibaba.fastjson.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;



/**
 * Created by bilibili on 2017/5/11.
 */
public class WxHtmlUtils {

    /**
     * 获取token 和openid
     * @throws Exception
     */
    public static Map<String,String> getTokenAndOpenid(String wxCode) throws Exception{

        String appid = ConfKit.get("AppId");
        String secret = ConfKit.get("AppSecret");

        String urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+wxCode+"&grant_type=authorization_code";
        URL url = new URL(urlStr);
        BufferedReader bufr = new BufferedReader(new InputStreamReader(new BufferedInputStream(url.openStream()), "utf-8"));
        String line;
        StringBuffer sb=new StringBuffer();
        while((line=bufr.readLine())!=null){
            sb.append(line);
        }
        bufr.close();
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        if(jsonObject.get("errcode") != null){
            throw new Exception(jsonObject.getString("errmsg"));
        }
        String access_token = String.valueOf(jsonObject.get("access_token"));
        String openid = String.valueOf(jsonObject.get("openid"));
        Map<String,String> map = new HashMap<>();
        map.put("access_token",access_token);
        map.put("openid",openid);
        return map;
    }

    /**
     * 获取用户信息
     * @throws Exception
     */
    public static Map<String,Object> getUserInfo(String access_token,String openid) throws Exception{

        String urlStr = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
        URL url = new URL(urlStr);
        BufferedReader bufr = new BufferedReader(new InputStreamReader(new BufferedInputStream(url.openStream()), "utf-8"));
        String line;
        StringBuffer sb=new StringBuffer();
        while((line=bufr.readLine())!=null){
            sb.append(line);
        }
        bufr.close();
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        if(jsonObject.get("errcode") != null){
            throw new Exception(jsonObject.getString("errmsg"));
        }

        Map<String,Object> map = new HashMap<>();
        map.put("openid",String.valueOf(jsonObject.get("openid")));
        map.put("nickname",String.valueOf(jsonObject.get("nickname")));
        map.put("sex",String.valueOf(jsonObject.get("sex")));
        map.put("city",String.valueOf(jsonObject.get("city")));
        map.put("province",String.valueOf(jsonObject.get("province")));
        map.put("country",String.valueOf(jsonObject.get("country")));
        map.put("headimgurl",String.valueOf(jsonObject.get("headimgurl")));
        return map;
    }
/*
    *//**
     *生成JS-SDK的页面必须先注入配置信息
     * @param urlParameter
     * @return
     *//*
    public static Map<String, String> createSignature(String urlParameter) throws Exception {
        String jsapi_ticket = WeixinApiTicket.getRecentTicket(R.getRecentToken());
        String urlAddress = urlParameter;
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = RandomUtils.getRandomString(32);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + urlAddress;

        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(string1.getBytes("UTF-8"));
        signature = byteToHex(crypt.digest());

        ret.put("url", urlAddress);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId",ConfKit.get("AppId"));
        return ret;
    }*/


    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }


}
